iT邦幫忙

2024 iThome 鐵人賽

DAY 17
0
  1. 先到主控台,選擇建立專案。

https://ithelp.ithome.com.tw/upload/images/20240927/201519562kIChXTWQ6.png

  1. (選用)看要不要開啟 Google Analytics 功能

https://ithelp.ithome.com.tw/upload/images/20240927/20151956OXFMlaEe5J.png

  1. 如果有選用 Google Analytics 功能,它會問你要連結到哪一個 Google Analytics 帳戶。

https://ithelp.ithome.com.tw/upload/images/20240927/20151956QRiVTOSYqk.png

  1. 來到專案首頁,點擊 Android 應用程式的符號。

https://ithelp.ithome.com.tw/upload/images/20240927/20151956cpOEsBnjl4.png

  1. 先去翻 app.json 找到 Android 的 block,找到 "package": "com.jim.notification" 顯示的 package name。
"android": {
      "adaptiveIcon": {
        "foregroundImage": "./assets/adaptive-icon.png",
        "backgroundColor": "#ffffff"
      },
      "package": "com.jim.notification"
    },
  1. 把 package name com.jim.notification 填入。暱稱是選填。

https://ithelp.ithome.com.tw/upload/images/20240927/20151956JOF21OBBeq.png

  1. 然後點擊"註冊應用程式"按鈕,接著下載 google-services.json 檔案。

  2. 把下載到的檔案丟到 React 專案裡的 android 資料夾目錄內。

We've added an import for Firebase Messaging:
javascriptCopyimport messaging from '@react-native-firebase/messaging';

We've introduced a new state variable fcmToken to store the FCM token:
javascriptCopyconst [fcmToken, setFcmToken] = useState('');

In the useEffect hook, we've added a call to register for FCM:
javascriptCopyregisterForFCM().then(token => token && setFcmToken(token));

We've added an FCM foreground message handler:
javascriptCopyconst unsubscribe = messaging().onMessage(async remoteMessage => {
console.log('FCM Message received in foreground:', remoteMessage);
// You can show a local notification here if needed
});

We've added a new function registerForFCM() to handle FCM registration:
javascriptCopyasync function registerForFCM() {
let token;
if (Device.isDevice) {
try {
await messaging().registerDeviceForRemoteMessages();
token = await messaging().getToken();
console.log('FCM Token:', token);
} catch (e) {
console.error('Error registering for FCM:', e);
}
}
return token;
}

We're now displaying both the Expo push token and the FCM token in the UI.

To use this setup:

Make sure you have set up Firebase in your project and have the necessary configuration files (google-services.json for Android and GoogleService-Info.plist for iOS).
Install the required dependencies:
Copynpx expo install @react-native-firebase/app @react-native-firebase/messaging

Configure your app.json as mentioned in the previous response, including the googleServicesFile paths.
Use the FCM token (fcmToken) to send push notifications through Firebase Cloud Messaging.


上一篇
[Day 16] 設定 Firebase FCM
下一篇
[Day 18] 設置 EAS CLI
系列文
跨平台協同:在 React Native 和 Kotlin 應用中實現無縫交互 -以 Notification 為例30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言